
package com.example.quicklaunch;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class AppListProvider extends ContentProvider {
    private static final UriMatcher sMatcher;
    public static final String AUTHORITY = "quicklaunch";
    private static final String UPDATE_APP_SQL = AppDataBaseHelper.APP_CLOUMN_PACKAGE + "=?";
    private static final int CODE_APP = 1;
    private AppDataBaseHelper mDataBaseHelper;

    static {
        sMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sMatcher.addURI(AUTHORITY, "app", CODE_APP);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        final int match = sMatcher.match(uri);
        SQLiteDatabase db = mDataBaseHelper.getWritableDatabase();
        switch (match) {
            case CODE_APP:
                db.delete(AppDataBaseHelper.TABLE_APP, selection, selectionArgs);
                break;
            default:
                break;
        }
        return 0;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        final int match = sMatcher.match(uri);
        SQLiteDatabase db = mDataBaseHelper.getWritableDatabase();
        switch (match) {
            case CODE_APP:
                db.insert(AppDataBaseHelper.TABLE_APP, null, values);
                break;
        }
        return null;
    }

    @Override
    public boolean onCreate() {
        if (mDataBaseHelper == null) {
            mDataBaseHelper = new AppDataBaseHelper(getContext());
        }
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        SQLiteDatabase db = mDataBaseHelper.getReadableDatabase();
        Cursor cursor = db.query(AppDataBaseHelper.TABLE_APP, projection, selection, selectionArgs,
                null, null, sortOrder);
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mDataBaseHelper.getWritableDatabase();
        int id = db.update(AppDataBaseHelper.TABLE_APP, values, UPDATE_APP_SQL, new String[] {
                values.getAsString(AppDataBaseHelper.APP_CLOUMN_PACKAGE)
        });
        return id;
    }

}
